import { restService } from "@/apis/rest"
import { IUser } from "@/apis/types"
import { useCrypto } from "@/hooks/useCrypto"
import { useLocalStorage } from "@/hooks/useLocalStorage"
import { RootState } from "@/store"
import { setState } from "@/utils/core"
import { formatDateTime } from "@/utils/dayjs"
import { ElMessage, ElMessageBox, FormInstance } from "element-plus"
import { Module } from "vuex"
import { ICamera } from "../CameraManagement/types"
import { IUserManagementActions, IUserManagementGetter, IUserManagementMutations, IUserManagementState } from "./types"

const state: IUserManagementState = {
    userList: [],
    userCount: 0,
    userListPageAndSize: {
        page: 1,
        size: 6
    },
    userFields: [
        { label: "ID", prop: "_id" },
        { label: "用户名", prop: "username" },
        { label: "密码", prop: "password" },
        { label: '邮箱', prop: 'email' },
        { label: "角色", prop: "role" },
        { label: '摄像头', prop: 'cameraStr' },
        { label: "创建时间", prop: "createdAt" },
        { label: "更新时间", prop: "updatedAt" }
    ],
    userForm: {
        username: "",
        password: "",
        email: '',
        role: "",
        camera: [],
        createdAt: "",
        updatedAt: ""
    },
    userFormComponent: {
        formStatus: "添加",
        formPlaceholder: {
            username: "请输入用户名",
            password: "请输入密码",
            email: "请输入邮箱",
            role: "请选择身份",
            camera: "请选择摄像头",
            createdAt: "请选择创建时间",
            updatedAt: "请选择更新时间"
        },
        formControl: {
            submit: {
                value: '提交',
                type: 'primary'
            },
            reset: {
                value: '重置',
                type: 'default'
            }
        }
    },
    userFormRules: {
        username: [
            { required: true, message: "请输入用户名", trigger: "blur" },
            { min: 6, message: "长度要大于等于6个字符", trigger: "blur" }
        ],
        password: [
            { required: true, message: "请输入密码", trigger: "blur" },
            { min: 6, message: "长度要大于等于6个字符", trigger: "blur" }
        ],
        email: [
            { required: true, message: "请输入邮箱", trigger: "blur" },
            { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
        ],
        role: [{ required: true, message: "请选择身份", trigger: "blur" }],
        camera: [{ required: true, message: "请选择摄像头", trigger: "blur" }],
        createdAt: [{ message: "请选择创建时间", trigger: "blur", default: new Date() }],
        updatedAt: [{ message: "请选择更新时间", trigger: "blur", default: new Date() }]
    },
    userRoleOpts: [
        { label: '管理员', value: 'admin' },
        { label: '普通用户', value: 'user' }
    ],
    userCameraOpts: [],
}

const actions: IUserManagementActions = {
    addUser: async ({ commit }, payload: IUser) => {
        commit("_addUser", payload)
    },
    deleteUser: async ({ commit }, { user, index }) => {
        if (user.role === 'admin') {
            ElMessage.error('管理员账户不可删除')
            return
        }
        ElMessageBox.confirm("此操作将永久删除该用户, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        })
            .then(async () => commit("_deleteUser", { user, index }))
            .catch(() => ElMessage.info("已取消删除"))
    },
    getAndUpdateUserList: async ({ commit }) => {
        commit("_getAndUpdateUserList")
    },
    modifyUser: async ({ commit }, payload: IUser) => {
        commit("_modifyUser", { ...payload })
        commit("_resetUserForm")
        ElMessage.success("修改成功")
    },
    submitForm: async ({ commit, state }, formEl: FormInstance | undefined) => {
        if (!formEl) return;
        formEl.validate(async (valid: boolean) => {
            if (valid) {
                commit('_addUser', state.userForm)
                return true;
            } else {
                ElMessage.warning("请检查需要提交的信息")
                return false;
            }
        })
    }
}

const mutations: IUserManagementMutations = {
    _setState: (state: IUserManagementState, { path, value }) => {
        setState(state, path, value);
    },
    _addUser: async (state: IUserManagementState, payload: IUser) => {
        const { encrypt } = useCrypto()
        const temp = { ...payload };
        temp.username = encrypt(payload.username)
        temp.password = encrypt(payload.password)
        const res = await restService("user", temp).add();
        if (res) {
            const user = { ...res };
            user.cameraStr = user.camera.map((cameraId) =>
                state.userCameraOpts.find(cameraOpt => cameraOpt.value === cameraId)?.label || '').join(',')
            state.userList.unshift(user)
            Object.keys(state.userForm).forEach(key => state.userForm[key] = '');
            ElMessage.success(`"${res.username}"添加成功`)
            state.userCount++;
        }
    },
    _deleteUser: async (state: IUserManagementState, { user, index }) => {
        const res = await restService("user", { _id: user._id }).del()
        if (res && !res.message) {
            state.userList.splice(index, 1)
            ElMessage.success(`"${res.username}"删除成功`)
            state.userCount--;
        }
    },
    _getAndUpdateUserList: async (state: IUserManagementState, pageAndSize = {}) => {
        const { setLocalStorage } = useLocalStorage()
        pageAndSize['page'] = pageAndSize['page'] || state.userListPageAndSize.page;
        pageAndSize['pageSize'] = pageAndSize['pageSize'] || state.userListPageAndSize.size;
        const res = (await restService("user", pageAndSize).getList()) as IUser[] | any
        if (res && !res.message) {
            const { decrypt } = useCrypto()
            state.userList = res.map((item: IUser) => {
                item.username && (item.username = decrypt(item.username))
                item.password && (item.password = decrypt(item.password))
                item.createdAt = formatDateTime(item.createdAt.toString());
                item.updatedAt = formatDateTime(item.updatedAt.toString());
                return item
            })

            state.userList = [...res]
            setLocalStorage("bishe-userList", state.userList)
        }
    },
    _resetUserForm: (state: IUserManagementState) => {
        Object.keys(state.userForm).forEach(key => state.userForm[key] = '');
    },
    _modifyUser: async (state: IUserManagementState, payload: IUser) => {
        const { encrypt } = useCrypto()
        state.userFormComponent.formStatus = '编辑'
        payload.username = encrypt(payload.username)
        payload.password = encrypt(payload.password)
        const res = await restService("user", payload).update()
        if (res) {
            state.userList = state.userList.map(item => {
                if (item._id === res._id) {
                    return res
                }
                return item
            })
        }
    },
    _getCameraList: async (state: IUserManagementState) => {
        const res = await restService("camera").getList()
        if (res) {
            state.userCameraOpts = res.map((item: ICamera) => {
                return {
                    label: item.name,
                    value: item._id
                }
            })
        }
    },
    _getUserCount: async (state: IUserManagementState) => {
        const res = await restService("user").getCount();
        if (res) {
            state.userCount = res.result;
        }
    },

}
const getters: IUserManagementGetter = {
    getUserList(state: IUserManagementState) {
        return state.userList
    },
    getSize(state: IUserManagementState) {
        return state.userListPageAndSize.size
    },
    getPage(state: IUserManagementState) {
        return state.userListPageAndSize.page
    },
    getUserCount(state: IUserManagementState) {
        return state.userCount
    }

}

export const userManagement: Module<IUserManagementState, RootState> = {
    namespaced: true,
    state,
    actions,
    mutations,
    getters
}
